import java.util.regex.Pattern as Pattern
import java.util.UUID as UUID
from javax.jms import MessageListener
from java.util import HashMap

class GetText(MessageListener):
	def __init__(self, socket_id):
		self.socket_id = socket_id

	def onMessage(self, m):
		t = m.text
		socket_manager.send(self.socket_id, t)

class SchmuckThinknetFilter(object):
	def __init__(self):
		self.regular_expression = Pattern.compile("^\[(.*?)\] (.*?[0-9a-zA-Z]+.*)")
		self.applet_launched = False
		self.thinknet_uuid = UUID.randomUUID().toString()

	def launch_applet(self, socket_id):
		if(self.applet_launched == False):
			props = HashMap()

			# The output queue is output from the muck socket
			props.put("thinknet-output-queue", "thinknet-output-queue-" + self.thinknet_uuid)

			# The input queue is user input that will be sent to the socket
			props.put("thinknet-input-queue", "thinknet-input-queue-" + self.thinknet_uuid)

			mq.subscribe("thinknet-input-queue-" + self.thinknet_uuid, GetText(socket_id))
			applet.runApplet("thinknet.xml", props)
			self.applet_launched = True

	def filter_text(self, socket_id, text):
		s = ""
		for style, string in text:
			s = s + string
		match = self.regular_expression.matcher(s)
		if(match.find()):
			self.launch_applet(socket_id)
			channel = match.group(1).split(' ')[0]
			mq.publish("thinknet-output-queue-" + self.thinknet_uuid, "%s;;%s" % (channel, match.group(2)))

		return [FILTER_CONTINUE, text]
 
schmuck_text_filters["thinknet"] = SchmuckThinknetFilter()